package edu.ptu.springboot04.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import edu.ptu.springboot04.common.controller.AjaxResponse;
import edu.ptu.springboot04.common.controller.BaseController;
import edu.ptu.springboot04.common.controller.TableDataInfo;
import edu.ptu.springboot04.domain.entity.Product;
import edu.ptu.springboot04.domain.vo.ProductVo;
import edu.ptu.springboot04.mapping.ProductMapping;
import edu.ptu.springboot04.service.IProductService;
import edu.ptu.springboot04.utils.JWTUtil;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @BelongsProject: springboot04
 * @BelongsPackage: edu.ptu.springboot04.controller
 * @Author: HYJ
 * @CreateTime: 2025-03-20  21:07
 * @Description: TODO
 * @Version: 1.0
 */
@RestController
@RequestMapping("/product")
public class ProductController extends BaseController {

    @Resource
    private IProductService productService;

    @GetMapping("/list")
    // 根据分类id、页码和每页数量查询商品列表
    public TableDataInfo pageList(Integer categoryId,
                                  // 默认页码为1
                                  @RequestParam(defaultValue = "1") Integer pageNum,
                                  // 默认每页数量为10
                                  @RequestParam(defaultValue = "10") Integer pageSize) {

        // 创建分页对象，设置页码和每页数量
        Page<Product> page = new Page<>(pageNum, pageSize);

        // 创建查询条件
        LambdaQueryWrapper<Product> wrapper = new LambdaQueryWrapper<>();

        // 添加查询条件，根据分类id查询
        wrapper.eq(Product::getCategoryId, categoryId);

        // 根据查询条件分页查询商品列表
        List<Product> products = productService.page(page, wrapper).getRecords();

        // 将商品列表转换为商品页面视图对象
        // 返回分页数据
        return dataTable(ProductMapping.INSTANCE.toProductPageVo(products), productService.count(wrapper));
    }

    @GetMapping("/get/{productId}")
    public AjaxResponse getProductById(@PathVariable Long productId, HttpServletRequest request) {
        Long userId = JWTUtil.getUserId(request);

        ProductVo productVoById = productService.getProductVoById(productId, userId);
        return productVoById != null ? AjaxResponse.success(productVoById) : AjaxResponse.failure("商品不存在");
    }
}
